/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package towerz.states;

import java.io.IOException;
import java.util.Vector;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.GameCanvas;
import towerz.component.Button;
import towerz.system.StateManager;
import towerz.system.StringManager;
import towerz.system.Utilities;

/**
 *
 * @author TimotiusNC
 */
public class StateGameOver extends GameState {
	public StateGameOver(int levelToRetry){
		super(GameState.GAME_OVER, StateManager.instance().getDarkImage());

		//Initialization
		m_Selected		= 0;
		m_LevelToRetry	= levelToRetry;
		try {
			m_GameOver		= Image.createImage(Utilities.BACKGROUND_FOLDER + "/gameover.png");
		} catch (IOException ex) {}

		initButtons();
	}

	private void initButtons(){
		//Create buttons
		m_Buttons = new Vector();

		m_Buttons.addElement(new Button(1, "/button-level.png", 70,  150, 3, StringManager.instance().getString("retry")));
        m_Buttons.addElement(new Button(1, "/button-level.png", 70,  190, 3, StringManager.instance().getString("main")));
	}

	public void update(long time, int keys) {
		//Super
		super.update(time, keys);

		//Change selection based on key
		if ((keys & GameCanvas.UP_PRESSED) != 0)	m_Selected--;
		if ((keys & GameCanvas.DOWN_PRESSED) != 0)	m_Selected++;

		//Correct selection
		if (m_Selected < 0) m_Selected = m_Buttons.size() - 1;
		m_Selected = m_Selected % m_Buttons.size();

		//If button is pressed
		if ((keys & GameCanvas.FIRE_PRESSED) != 0) { //Goto GAME state
			((Button)m_Buttons.elementAt(m_Selected)).setState(Button.STATE_PRESSED);

			//Based on the currently selected
			switch(m_Selected){
                case 0: //Retry
					Vector param = new Vector(1);
					param.addElement(new Integer(m_LevelToRetry));
					
					StateManager.instance().goTo(GameState.LOADING, param, true);
                    break;
                case 1: //Back to main menu
                    StateManager.instance().goTo(GameState.FRONT, null, false);
                    break;
            }
		}

		//Restart state
		for (int i = 0; i < m_Buttons.size(); i++) {
			((Button)m_Buttons.elementAt(i)).setState(Button.STATE_NONE);
		}

		//Manage the selected button state
		((Button)m_Buttons.elementAt(m_Selected)).setState(Button.STATE_SELECTED);
	}

	public void draw(Graphics g) {
		//Super
		super.draw(g);
		
		//Draw
		g.drawImage(m_GameOver, StateManager.instance().getWidth() / 2, StateManager.instance().getHeight() / 2, Graphics.HCENTER | Graphics.VCENTER);

		//Draw buttons
		for (int i = 0; i < m_Buttons.size(); ++i) {
			((Button)m_Buttons.elementAt(i)).draw(g);
		}
	}

	//DATA
	protected int		m_Selected;
	protected int		m_LevelToRetry;
	protected Image		m_GameOver;
	protected Vector	m_Buttons;
}
